<template>
  <el-form
    label-position="left"
    ref="form"
    :model="form"
    :label-width="`${maxWidth}px`"
  >
    <el-form-item
      v-for="(item, idx) in formTemplate"
      :key="idx"
      :label="item.label"
    >
      <!-- 如果是input框 -->
      <el-input
        v-if="item.type === 'input'"
        v-model="form[item.key]"
        :disabled="item.disabled"
      ></el-input>
      <!-- 如果是选择框 -->
      <el-select
        v-else-if="item.type === 'select'"
        v-model="form[item.key]"
        :placeholder="item.placeholder"
      >
        <el-option
          v-for="o in item.opts"
          :key="o.value"
          :label="o.label"
          :value="o.value"
        ></el-option>
      </el-select>
      <!-- 如果是多选框，name不知道是什么，但是大家都是一样的-->
      <el-checkbox-group
        v-else-if="item.type === 'checkbox'"
        v-model="form[item.key]"
      >
        <el-checkbox
          v-for="o in item.opts"
          :key="o.label"
          :label="o.label"
          :name="item.key"
        ></el-checkbox>
      </el-checkbox-group>
      <!-- 如果是单选框 -->
      <el-radio-group
        v-else-if="item.type === 'radio'"
        v-model="form[item.key]"
      >
        <el-radio v-for="o in item.opts" :key="o.label" :label="o"></el-radio>
      </el-radio-group>
      <!-- 如果是开关 -->
      <el-switch
        v-else-if="item.type === 'switch'"
        v-model="form[item.key]"
      ></el-switch>
      <!-- 如果是日期选择器 -->
      <el-date-picker
        v-else-if="item.type === 'date_picker'"
        type="date"
        :placeholder="item.placeholder"
        v-model="form[item.key]"
        style="width: 100%"
      ></el-date-picker>
      <!-- 如果是时间选择器 -->
      <el-time-picker
        v-else-if="item.type === 'time_picker'"
        :placeholder="item.placeholder"
        v-model="form[item.key]"
        style="width: 100%"
      ></el-time-picker>
    </el-form-item>
    <slot></slot>
  </el-form>
</template>

<script>
// 这个数据可以从外面传
/**
 *
 */
const fontSize = 14;

export default {
  props: ["formTemplate", "form"],
  computed: {
    formInit() {
      let obj = {};
      this.formTemplate.forEach((e) => {
        if (e.type == "checkbox") {
          obj[e.key] = [];
        } else if (e.type == "switch") {
          obj[e.key] = false;
        } else {
          obj[e.key] = "";
        }
      });
      return obj;
    },
    maxWidth() {
      let maxLen = 0;
      this.formTemplate.forEach((e) => {
        if (maxLen < e.label.length) maxLen = e.label.length;
      });
      return maxLen * fontSize + fontSize;
    },
  },
  mounted() {
    if (this.form === undefined) {
      this.form = this.formInit;
    }
  },
};
</script>

<style lang='less' scoped>
.el-form {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: flex-start;
  .el-form-item {
    display: flex;
    flex-direction: row;
    margin-bottom: 10px;
  }
}
</style>